package com.wwj.admin.system.controller;

import com.wwj.core.system.entity.Role;
import com.wwj.core.system.service.IRoleService;
import com.wwj.framework.controller.BaseController;
import com.wwj.framework.utils.ReturnData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by xya on 16-10-25.
 */
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

    public static final String INDEX = "/admin/system/role";

    @Resource
    private IRoleService roleService;


    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    public ModelAndView index() {
        try {
            List<Role> roles = roleService.findAllRole();
            return new ModelAndView(INDEX, "roles", roles);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ModelAndView(ERROR);
        }

    }

    @RequestMapping("/{id}")
    @ResponseBody
    public ReturnData listData(@PathVariable("id") Integer id) {
        try {
            Role role = roleService.findRoleById(id);
            return new ReturnData().success(role);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public ReturnData saveOrUpdate(Role role) {
        try {
            roleService.saveOrUpdate(role);
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    @RequestMapping("/remove")
    @ResponseBody
    public ReturnData remove(Integer id) {
        try {
            roleService.removeRole(new Integer[]{id});
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    @RequestMapping(value = "/check")
    @ResponseBody
    public boolean check(String key, String value, HttpSession session) {
        try {
            switch (key) {
                case "code":
                    return !roleService.checkRoleCode(value);
                case "name":
                    return !roleService.checkRoleName(value);
                default:
                    return false;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }
}
